package org.caro.actions.play;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.ImageIcon;
import javax.swing.JButton;

import org.caro.actions.ContestantAction;
import org.caro.gui.ActionZonePanel;
import org.caro.gui.UtilityZonePanel;
import org.caro.utils.CheckWinner;
import org.caro.utils.Constants;
import org.caro.utils.Position;

public class ReceivePlayChess extends Thread {
	private Socket socket;
	private BufferedReader bufferedReader;
	private String host;
	private int port;
	private int mode;
	private ActionZonePanel actionZone;

	public ReceivePlayChess(String host, int port, int mode) {
		super("receive play");
		this.host = host;
		this.port = port;
		this.mode = mode;
	}

	@Override
	public void run() {
		try {
			if (mode == Constants.HOST) {
				ServerSocket server = new ServerSocket(port);
				socket = server.accept();
				server.close();
			} else
				socket = new Socket(host, port);
			bufferedReader = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			while (true) {
				String recvMessage = bufferedReader.readLine();
				Position pos = new Position(recvMessage);
				JButton actionButton = actionZone.getButton()[pos.getX()][pos
						.getY()];
				if (this.mode == Constants.HOST) {
					actionButton.setIcon(new ImageIcon(Constants.IMAGE_PLAYER_2));
					actionZone.getMapButton()[pos.getX()][pos.getY()] = Constants.PLAYER2;
					if (CheckWinner.winner(actionZone.getMapButton(),
							pos.getX(), pos.getY(), Constants.PLAYER2) == Constants.PLAYER2) {
							
					}
				} else {
					actionButton
							.setIcon(new ImageIcon(Constants.IMAGE_PLAYER_1));
					actionZone.getMapButton()[pos.getX()][pos.getY()] = Constants.PLAYER1;
				}
				ContestantAction.turn = true;
			}
		} catch (Exception ex) {
		}
	}

	public void doAction(ActionZonePanel actionZone,
			UtilityZonePanel utilityZone) {
		this.actionZone = actionZone;
		start();
	}

	public void closeConnection() throws Exception {
		bufferedReader.close();
		socket.close();
	}
}
